/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: GetParams.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.network.params;

import android.text.TextUtils;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import io.bhex.baselib.network.request.GetRequestBuilder;
import io.bhex.baselib.utils.DebugLog;


public class GetParams extends AbstractParams implements IGetParams {
    private static final long serialVersionUID = -1220428192068000189L;
    private Map<String, Object> getParamsMap;

    private String urlString = null;
    private URL urlObject = null;

    public GetParams(Builder<? extends Builder, ? extends GetParams> builder) {
        super(builder);

        getParamsMap = new HashMap<>();

        if (builder.baseParams != null)
            getParamsMap.putAll(builder.baseParams.getParams());

        getParamsMap.putAll(builder.getParams);
    }

    @Override
    public String getUrl() {
        if (urlString == null) {
            urlString = generateUrlWithParams();
        }

        return urlString;
    }

    @Override
    public URL getUrlObject() {
        if (urlObject != null) {
            return urlObject;
        }

        if (urlString == null) {
            urlString = generateUrlWithParams();
        }

        try {
            urlObject = new URL(urlString);
        } catch (MalformedURLException e) {
            // todo: 暂时吞掉url解析错误
            e.printStackTrace();
        }

        return urlObject;
    }

    private String generateUrlWithParams() {
        if (getParamsMap.isEmpty()) {
            return url;
        }

        if (TextUtils.isEmpty(url)) {
            return "";
        }

        StringBuilder builder = new StringBuilder(url);

        if (builder.indexOf("?") == -1) {
            builder.append("?");
        } else {
            builder = new StringBuilder(builder.substring(0, builder.indexOf("?") + 1));
        }

        for (String key : getParamsMap.keySet()) {
            builder.append(key + "=" + getParamsMap.get(key) + "&");
        }

        return builder.substring(0, builder.length() - 1);
    }

    @Override
    public Map<String, Object> getParams() {
        return getParamsMap;
    }

    @Override
    public String getRequestBuilderClazz() {
        return GetRequestBuilder.class.getName();
    }

    public static class Builder<B extends Builder, P extends GetParams> extends AbstractParams.Builder<B, P> {

        private Map<String, Object> getParams = new HashMap<>();

        /**
         * 用 {@link #addParam(String, Object)} 代替
         *
         * @param key
         * @param value
         * @return
         */
        @Deprecated

        public B addGetParams(String key, Object value) {
            return addParam(key, value);
        }

        @Override
        public B addParam(String key, Object value) {
            try {
                getParams.put(key, URLEncoder.encode(value.toString(), "UTF-8"));
            } catch (Exception e) {
                DebugLog.e(e);
                getParams.put(key, value);
            }


            return (B) this;
        }

        @Override
        public P build() {
            return (P) new GetParams(this);
        }
    }
}
